<template>
  <view class="message-container">

    <!-- 消息列表 -->
    <view class="content-area">
      <!-- 未读消息区域 -->
      <view class="section" v-if="unreadMessages.length > 0">
        <view class="section-title">
          <text>未读消息</text>
          <text class="count">({{ unreadMessages.length }})</text>
        </view>
        <view class="message-list">
          <view 
            v-for="item in unreadMessages" 
            :key="item.id"
            class="message-item unread"
            @click="handleMessageClick(item)"
          >
            <view class="message-header">
              <view class="left">
                <text class="dot"></text>
                <text class="title">{{ item.title }}</text>
              </view>
              <text class="time">{{ formatTime(item.createdAt) }}</text>
            </view>
            
            <view class="message-content" v-if="item.isExpanded">
              <text class="content">{{ item.content }}</text>
              <!-- 预约相关信息 -->
              <view class="appointment-info" v-if="item.appointmentId">
                <view class="info-item">
                  <text class="label">预约日期：</text>
                  <text class="value">{{ item.appointmentDate }}</text>
                </view>
                <view class="info-item">
                  <text class="label">时间段：</text>
                  <text class="value">{{ formatPeriod(item.appointmentTime) }}</text>
                </view>
                <view class="info-item">
                  <text class="label">支付状态：</text>
                  <text class="value" :class="item.paymentStatus">
                    {{ formatPaymentStatus(item.paymentStatus) }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 已读消息区域 -->
      <view class="section" v-if="readMessages.length > 0">
        <view class="section-title">
          <text>已读消息</text>
          <text class="count">({{ readMessages.length }})</text>
        </view>
        <view class="message-list">
          <view 
            v-for="item in readMessages" 
            :key="item.id"
            class="message-item"
            @click="handleMessageClick(item)"
          >
            <view class="message-header">
              <text class="title">{{ item.title }}</text>
              <text class="time">{{ formatTime(item.createdAt) }}</text>
            </view>
            
            <view class="message-content" v-if="item.isExpanded">
              <text class="content">{{ item.content }}</text>
              <!-- 预约相关信息 -->
              <view class="appointment-info" v-if="item.appointmentId">
                <view class="info-item">
                  <text class="label">预约日期：</text>
                  <text class="value">{{ item.appointmentDate }}</text>
                </view>
                <view class="info-item">
                  <text class="label">时间段：</text>
                  <text class="value">{{ formatPeriod(item.appointmentTime) }}</text>
                </view>
                <view class="info-item">
                  <text class="label">支付状态：</text>
                  <text class="value" :class="item.paymentStatus">
                    {{ formatPaymentStatus(item.paymentStatus) }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 无消息提示 -->
      <view class="empty-tip" v-if="!messages.length">
        <image src="/static/images/empty.png" mode="aspectFit"></image>
        <text>暂无消息通知</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getNotifications, markAsRead } from '@/api/notification'

export default {
  data() {
    return {
      messages: [],
      loading: false
    }
  },

  computed: {
    // 未读消息
    unreadMessages() {
      return this.messages
        .filter(item => item.status === 'unread')
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    },
    // 已读消息
    readMessages() {
      return this.messages
        .filter(item => item.status === 'read')
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    }
  },

  onShow() {
    this.getMessageList()
  },

  // 支持下拉刷新
  onPullDownRefresh() {
    this.getMessageList()
  },

  methods: {
    // 获取消息列表
    async getMessageList() {
      try {
        this.loading = true
        const userIdStr = uni.getStorageSync('userId')
        console.log('userIdStr:', userIdStr)
        if (!userIdStr) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }, 1500)
          return
        }



        const res = await getNotifications(userIdStr)  // 直接传递数字类型的userId
        
        // 为每条消息添加展开状态标记
        this.messages = res.map(item => ({
          ...item,
          isExpanded: false
        }))
        
      } catch (error) {
        console.error('获取消息列表失败：', error)
        uni.showToast({
          title: '获取消息失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    // 处理消息点击
    async handleMessageClick(message) {
      // 切换展开状态
      message.isExpanded = !message.isExpanded
      
      // 如果是未读消息，标记为已读
      if (message.status === 'unread') {
        try {
          const userId = uni.getStorageSync('userId')
          await markAsRead(message.id, userId)
          message.status = 'read'
        } catch (error) {
          console.error('标记已读失败：', error)
        }
      }
    },

    // 格式化时间
    formatTime(dateStr) {
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },

    // 格式化时间段
    formatPeriod(period) {
      const periodMap = {
        morning: '上午',
        afternoon: '下午'
      }
      return periodMap[period] || period
    },

    // 格式化支付状态
    formatPaymentStatus(status) {
      const statusMap = {
        paid: '已支付',
        unpaid: '待支付',
        refunded: '已退款'
      }
      return statusMap[status] || status
    }
  }
}
</script>

<style lang="scss">
.message-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100rpx;
  
  .header {
    padding: 30rpx 40rpx;
    background: #fff;
    border-bottom: 1rpx solid #eee;
    
    .title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .content-area {
    padding: 20rpx;
  }

  .section {
    margin-bottom: 20rpx;

    .section-title {
      padding: 20rpx;
      font-size: 28rpx;
      color: #666;
      display: flex;
      align-items: center;

      .count {
        margin-left: 10rpx;
        color: #999;
      }
    }
  }

  .message-list {
    .message-item {
      background: #fff;
      margin-bottom: 20rpx;
      padding: 30rpx;
      border-radius: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s;

      &.unread {
        background: #f0f7ff;
        border-left: 8rpx solid #007AFF;
      }

      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .left {
          display: flex;
          align-items: center;
          flex: 1;

          .dot {
            width: 12rpx;
            height: 12rpx;
            background: #007AFF;
            border-radius: 50%;
            margin-right: 16rpx;
          }

          .title {
            font-size: 32rpx;
            color: #333;
            font-weight: 500;
          }
        }

        .time {
          font-size: 24rpx;
          color: #999;
          margin-left: 20rpx;
        }
      }

      .message-content {
        .content {
          font-size: 28rpx;
          color: #666;
          line-height: 1.6;
          margin: 20rpx 0;
        }

        .appointment-info {
          background: #f8f9fa;
          border-radius: 12rpx;
          padding: 24rpx;
          margin-top: 16rpx;

          .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 16rpx;

            &:last-child {
              margin-bottom: 0;
            }

            .label {
              color: #666;
              font-size: 26rpx;
              width: 140rpx;
            }

            .value {
              color: #333;
              font-size: 26rpx;
              flex: 1;

              &.paid {
                color: #52c41a;
              }

              &.unpaid {
                color: #f5222d;
              }

              &.refunded {
                color: #faad14;
              }
            }
          }
        }
      }

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }
  }

  .empty-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 200rpx;

    image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 30rpx;
    }

    text {
      font-size: 28rpx;
      color: #999;
    }
  }
}
</style> 